<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/24
 * Time: 16:38
 */

namespace app\console\controller;
use think\Controller;
use think\Db;
use think\Request;
use app\console\model\MemberCard as Model;
use think\Url;


class MemberCard extends Controller
{
    protected $beforeActionList = [
        'shop_list'  =>[]
    ];

    public function shop_list()
    {
        $where = [];
        if(\session('auding_status') == 1){
            $where['id'] = ['eq',\session('shop_id')];
        }
        $shop_list = Db::name('shop s')->field('id,shop_title')->where($where)->select();
        $this->assign('shop_list', $shop_list);
    }
    public function index(Model $model)
    {
        $param = Request::instance()->param();
        $where = [];
        if(\session('auding_status') == 1){
            $where['mc.shop_id'] = ['eq',\session('shop_id')];
        }else{

        }
        if (!empty($param['interval_timer'])) {
            $interval_timer = explode('/', $param['interval_timer']);
            $where['mc.create_time'] = ['between', [$interval_timer[0], $interval_timer[1]]];
        }
        if(!empty($param['title'])) $where['m.username'] = ['like','%'.$param['title'].'%'];
        if(!empty($param['shop_id'])) $where['mc.shop_id'] = ['eq', $param['shop_id']];
        $data = $model
            ->alias('mc')
            ->join('member m','mc.member_id = m.id','left')
            ->join('shop s','mc.shop_id = s.id','left')
            ->field('mc.*,s.shop_title,m.car_number')
            ->where($where)
            ->order('mc.id','desc')
            ->paginate(10, false, ['query' => $param]);
        $count = $model
            ->alias('mc')
            ->join('member m','mc.member_id = m.id','left')
            ->join('shop s','mc.shop_id = s.id','left')
            ->field('mc.*,s.shop_title')
            ->where($where)
            ->order('mc.id','desc')->count();
        return view('', ['data' => $data,'count' => $count]);
    }

    public function daochu(Model $model){
        $param = Request::instance()->param();
        $where = [];
        if(\session('auding_status') == 1){
            $where['mc.shop_id'] = ['eq',\session('shop_id')];
        }else{

        }
        if(!empty($param['title'])) $where['m.username'] = ['like','%'.$param['title'].'%'];
        if (!empty($param['shop_id'])) $where['mc.shop_id'] = ['eq', $param['shop_id']];
        if (!empty($param['interval_timer'])) {
            $interval_timer = explode('/', $param['interval_timer']);
            $where['mc.create_time'] = ['between', [$interval_timer[0], $interval_timer[1]]];
        }
        $data = $model
            ->alias('mc')
            ->join('member m','mc.member_id = m.id','left')
            ->join('shop s','mc.shop_id = s.id','left')
            ->field('mc.*,m.car_number,s.shop_title')
            ->where($where)
            ->order('mc.id','desc')
            ->paginate(10000, false, ['query' => $param])->toArray();
        if(!empty($data)){
            foreach ($data['data'] as $k => &$v){
                $v['username'] = hideStr($v['username'],1,6);
                if(empty($v['shop_title'])){
                    $v['shop_title'] = '平台发放';
                }
                switch ($v['type']){
                    case 1;
                    $v['type'] = '年卡';
                    break;
                    case 2;
                    $v['type'] = '次卡';
                    break;
                }
                switch ($v['count']){
                    case 10000;
                        $v['count_type'] = '无限';
                        break;
                    default;
                        $v['count_type'] = $v['count'].'('.$v['minus_count'].')';
                }

            }
        }

        $this->push_coupon($data['data'],'用户会员卡导出');
    }
    public function push_coupon($data,$name = 'Excel')
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        error_reporting(E_ALL);
        date_default_timezone_set('Asia/Shanghai');

        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');
        $objPHPExcel = new \PHPExcel();

        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("管理员")
            ->setLastModifiedBy("管理员")
            ->setTitle("电话本导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("备份数据")
            ->setKeywords("excel")
            ->setCategory("result file");
        $objPHPExcel->setActiveSheetIndex(0)
            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
            ->setCellValue('A1', 'ID')
            ->setCellValue('B1', '会员卡用户')
            ->setCellValue('C1', '车牌号')
            ->setCellValue('D1', '发放门店')
            ->setCellValue('E1', '会员卡类型')
            ->setCellValue('F1', '总次数-剩余次数')
            ->setCellValue('G1', '开始时间 / 结束时间')
            ->setCellValue('H1', '发放时间')

        ;
        $sheet1 = ['A', 'B', 'C', 'D', 'I'];

        for ($x = 0; $x < count($sheet1); $x++) {
            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(
                array(
                    'font'      => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' =>
                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
            );
        }

        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/

        $n = 0;
        foreach ($data as $v) {

            $num = $n + 2;
            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
                ->setCellValue('A' . $num, $v['id'])
                ->setCellValue('B' . $num, $v['username'])
                ->setCellValue('C' . $num, $v['car_number'])
                ->setCellValue('D' . $num, $v['shop_title'])
                ->setCellValue('E' . $num, $v['type'])
                ->setCellValue('F' . $num, $v['count_type'])
                ->setCellValue('G' . $num, $v['start_time'].'/'.$v['end_time'])
                ->setCellValue('H' . $num, $v['create_time'])
            ;

            $n++;
        }

        $objPHPExcel->getActiveSheet(0)->setTitle('用户会员卡导出');
        $objPHPExcel->setActiveSheetIndex(0);

        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }

    public function update($id, Request $request, Model $coupon)
    {

        if ($request->instance()->isPost()) {

            $data = $request->instance()->param();

            $dispose = $coupon->allowField(true)->save($data, ['id' => $id]);
            if ($dispose !== false) {
                win('操作成功', Url::build('index'));
            }
            fail('操作失败');
        }

        $item = Model::get($id);

        $SystemCard = (new \app\console\model\SystemCard())
            ->alias('mc')
            ->field('mc.*')
            ->order('mc.id','desc')
            ->select();
        return $this->fetch('create', [
            "mate_title" => '会员卡',
            'item' => $item,
            'SystemCard' => $SystemCard,
            'member_list' => Db::name('member')->select()

        ]);
    }

    public function create(Request $request, Model $coupon)
    {

        if ($request->instance()->isPost()) {
            $data = $request->instance()->param();
            if(isset($data['order_is_free']) === false){
                $data['order_is_free'] = 1;
            }
            //$dispose = $coupon->allowField(true)->save($data);
            $url = Request::instance()->domain().url('index/gift_order/create_member_card');
            $array = ['id' => $data['system_card_id'] ,'t_type' => 2,'member_id' => $data['member_id'],'shop_id' => $data['shop_id'],'order_is_free' => $data['order_is_free']];
            $system_card = Db::name('system_card')->where('id',$data['system_card_id'])->find();
            $ret = self::http_request($url,$array);
            $ret = \GuzzleHttp\json_decode($ret,true);
            if ($ret['code'] == 200) {
                if ($system_card['type'] == 2) {
                    $system_card['type'] = 2; //如果是次卡不绑定
                } else {
                    if (isset($data['car_number'])) {
                        Db::name('member')->where('id', $data['member_id'])->setField('car_number', $data['car_number']);
                    }
                }
                //(new \app\index\controller\MemberMessage())->jpushMessage($data['member_id'],'您的会员卡订单已创建,请查看','可用于汽车服务类',3);
                $this->redirect('console/gift_order/update',['id' => $ret['order_id']]);
                win('操作成功', Url::build('console/gift_order/update',['id' => $ret['order_id']]));
            }else{
                halt($ret);
            }
            fail('操作失败');
        }
        if(session('auding_status') == 1){
            //$shop_id = session('shop_id');
        }else{
            //$shop_id = 0;
        }

        $SystemCard = (new \app\console\model\SystemCard())
            ->alias('mc')
            ->field('mc.*')
            ->order('mc.id','desc')
            ->where('auding_status',2)
            ->select();
        $manage_array = Db::name('manager')->where('level = 2 and is_allow = 2 or level = 1 or level = 5 and is_allow = 2 ')->column('id');
        //echo Db::getLastsql();
        return $this->fetch('create', [
            "mate_title" => '会员卡',
            'SystemCard' => $SystemCard,
            'manage_array' => implode(',',$manage_array),
            'member_list' => Db::name('member')->select()

        ]);
    }

    public static function http_request($url, $data = null)
    {

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;

    }

    public function destroy($id){
        $ret = (new \app\console\model\MemberCard())->where('id',$id)->delete();
        if($ret){
            win('删除成功',Url::build('index'));
        }
        fail('删除失败');
    }
}